<template>
  <div id="echartsList">
    <h3 class="echarts-title">
      总活跃用户数统计
      <popover :descriptionData="activityData"></popover>
    </h3>
    <!--上部搜索条件组件-->
    <topSearch
      :form-inline="formInline"
      @toSearch="toSearch"
      @setTypeList="setTypeList"
    ></topSearch>
    <div class="table-conBtn">
      <el-button
        v-permission="'wh:system:activeAnalysis:export'"
        type="warning"
        icon="el-icon-download"
        @click="exportData"
      >
        导出
      </el-button>
      <freshCom @searchList="searchList"></freshCom>
    </div>
    <el-radio-group v-model="activityAnalysisType" class="date-btn">
      <el-radio-button
        v-for="item in activityAnalysisTypeList"
        :label="item.dictValue"
        :key="item.dictValue"
      >
        {{ item.dictLabel }}</el-radio-button
      >
    </el-radio-group>
    <div id="activityEcharts"></div>
  </div>
</template>

<script>
import {
  getChartsList,
  exportTable1,
  exportTable2,
  getTable
} from '@/api/dataStatistics/activityAnalysis/index.js' // 接口
import topSearch from '@component/dataStatistics/activityAnalysis/topSearch' // 上部搜索条件
import popover from '@component/dataStatistics/common/popover' // 注释说明
import { getInterval } from '@utils/pubFunction'
export default {
  name: 'echarts',
  msg: '活跃分析-图表',
  props: ['powerAry'],
  components: {
    topSearch,
    popover
  },
  watch: {
    activityAnalysisType(newV, oldV) {
      /*日/周/月*/
      /* console.log('日期变了')*/
      if (!this.clickSearch) {
        this.searchList()
      }
    }
  },
  data() {
    return {
      clickSearch: false, //是否点击查询按钮
      myCharts: null,
      formInline: {
        startDate: '', // 开始时间
        endDate: '', // 结束时间
        createTime: []
      },
      activityAnalysisType: 'DAY',
      activityAnalysisTypeList: [],
      option: {
        title: [
          {
            text: ' \n日期\nAPP\nPC\nM站\n总活跃人数\n去重活跃人数',
            bottom: 30,
            left: 2,
            textStyle: {
              lineHeight: 40,
              fontSize: 13,
              fontWeight: 'normal',
              formatter: function(value) {
                return '{table|' + value + '}'
              },
              rich: {
                table: {
                  align: 'center'
                }
              }
            }
          }
        ],
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#283b56'
            }
          }
        },
        legend: {
          data: [
            '总活跃人数',
            '去重活跃人数',
            '正式用户',
            '定金用户',
            '试学用户',
            '无身份'
          ],
          left: 40
        },
        grid: {
          bottom: 273,
          left: 90,
          right: 100
        },
        dataZoom: {
          /* show: false,
          type: 'slider',*/
          zoomLock: true
          /*zoomOnMouseWheel:false*/
          /* start: 0,
          end: 50*/
        },
        xAxis: [
          {
            type: 'category',
            boundaryGap: false,
            axisTick: {
              length: 228
            },
            axisLabel: {
              align: 'left',
              interval: 0,
              rich: {
                table: {
                  lineHeight: 20,
                  align: 'center'
                }
              }
            }
          }
        ],
        yAxis: [
          {
            type: 'value',
            scale: true,
            minInterval: 1,
            /* name: '数量',*/
            splitLine: {
              show: false
            },
            min: function(v) {
              return Math.max(v.min - 10, 0)
            }
          }
        ],
        series: [
          { type: 'line', areaStyle: {} },
          { type: 'line', areaStyle: {} },
          { type: 'line', areaStyle: {} },
          { type: 'line', areaStyle: {} },
          { type: 'line', areaStyle: {} },
          { type: 'line', areaStyle: {} }
        ]
      },
      defaultOpt: {
        app: [],
        money: [],
        mz: [],
        normal: [],
        other: [],
        pc: [],
        title: [],
        total: [],
        totalPerson: [],
        threeAppsSum: [],
        tryNum: []
      },
      tableLength: 0 //下方表格有几行数据
    }
  },
  computed: {
    activityData() {
      return this.$store.state.descriptionData.activityData
    }
  },
  mounted() {
    this.echartsInit()
  },
  methods: {
    echartsInit() {
      this.myCharts = this.echarts.init(
        document.getElementById('activityEcharts')
      )
      let _this = this
      $(window).resize(function() {
        //这里写内容
        _this.myCharts.resize()
      })
      this.myCharts.setOption(this.option)
    },
    /* 获取字典状态 */
    setTypeList(list) {
      this.activityAnalysisTypeList = [...list]
      this.$nextTick(() => {
        this.activityAnalysisType = this.activityAnalysisTypeList[0].dictValue
        this.searchList()
      })
    },
    /*获取图表数据*/
    searchList() {
      let _this = this
      Promise.all([_this.getEcahrtsInfo(), _this.getTable()]).then(
        ([res1, res2]) => {
          let data = { ...res1, ...res2 }
          /* let data = { ...this.defaultOpt }*/
          /* console.log(data)*/
          _this.clickSearch = false
          _this.myCharts.showLoading()
          var lineList = _this.getTableLine(_this.tableLength)
          /*计算x轴间隔*/
          let dataLength = data.title.length
          let interval = 0
          if (dataLength > 30) {
            interval = getInterval(dataLength, 30)
          }
          //计算 dataZoom 结束位置
          let dataZoom = { show: false }
          if (data.title.length > 15) {
            let endV = (interval + 1) * 15 - 1
            dataZoom = {
              show: true,
              moveOnMouseMove: false,
              type: 'slider',
              /*  zoomLock:true,*/
              startValue: 0,
              endValue: endV
            }
          }

          let opt = {
            dataZoom: dataZoom,
            xAxis: [
              {
                data: data.title,
                axisLabel: {
                  formatter: function(value, index) {
                    var indexNum = 0
                    for (var i = 0; i < data.title.length; i++) {
                      if (value == data.title[i]) {
                        indexNum = i
                      }
                    }
                    return (
                      '{table| ' +
                        value +
                        '}\n{table|' +
                        data.app[indexNum].everySourceUserCount +
                        '\n 占比 ' +
                        data.app[indexNum].proportionLevel +
                        '}\n{table|' +
                        data.pc[indexNum].everySourceUserCount +
                        '\n 占比 ' +
                        data.pc[indexNum].proportionLevel +
                        '}\n{table|' +
                        (data.mz.length &&
                          data.mz[indexNum].everySourceUserCount) ||
                      0 +
                        '\n 占比 ' +
                        data.mz[indexNum].proportionLevel +
                        '}\n{table|' +
                        '\n ' +
                        data.threeAppsSum[indexNum] +
                        '}\n{table|\n' +
                        data.totalPerson[indexNum] +
                        '}\n{table|}'
                    )
                  },
                  interval: interval
                }
              }
            ],
            series: [
              { name: '总活跃人数', data: data.sumTotal },
              { name: '去重活跃人数', data: data.total },
              { name: '正式用户', data: data.normal },
              { name: '试学用户', data: data.tryNum },
              { name: '定金用户', data: data.money },
              { name: '无身份', data: data.other }
            ],
            graphic: lineList
          }
          _this.myCharts.setOption(opt)
          _this.myCharts.hideLoading()
        }
      )
    },
    /*获取图表信息*/
    getEcahrtsInfo() {
      return new Promise((resolve, reject) => {
        let obj = {
          ...this.formInline,
          ...{ activityAnalysisType: this.activityAnalysisType }
        }
        delete obj.createTime
        getChartsList(
          obj,
          (response) => {
            let obj = response[0]
            let {
              eventDate: title,
              activityTotalCount: total, //去重活跃
              identityTotalSum: sumTotal, //总活跃
              everyActivityCount: {
                TRY: tryNum,
                FORMAL: normal,
                OTHER: other,
                DEPOSIT: money
              }
            } = obj
            let res1 = { title, total, sumTotal, tryNum, normal, other, money }
            resolve(res1)
          },
          (response) => {
            this.$message({
              message: response.message,
              type: 'warning'
            })
            reject()
          }
        )
      })
    },
    /*获取表格信息*/
    getTable() {
      let _this = this
      return new Promise((resolve, reject) => {
        let obj = {
          ...this.formInline,
          ...{ activityAnalysisType: this.activityAnalysisType }
        }
        delete obj.createTime
        getTable(
          obj,
          (response) => {
            _this.tableLength = Object.keys(response).length
            let obj = response
            let { app, pc, m: mz, total: totalPerson, threeAppsSum } = obj
            let res2 = {
              app,
              pc,
              mz,
              totalPerson,
              threeAppsSum
            }
            resolve(res2)
          },
          (response) => {
            this.$message({
              message: response.message,
              type: 'warning'
            })
            reject()
          }
        )
      })
    },
    getTableLine(num) {
      var list = []
      var bottom = 245
      var height = 40
      for (var i = 0; i < num; i++) {
        list.push({
          type: 'line',
          bottom: bottom - i * height,
          right: 0,
          style: {
            fill: '#333'
          },
          shape: {
            x1: 0,
            y1: 0,
            x2: 3200,
            y2: 0
          }
        })
      }
      return list
    },
    /* 导出 */
    exportData() {
      this.$confirm('确定导出当前数据吗？', '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let obj = {
          ...this.formInline,
          ...{ activityAnalysisType: this.activityAnalysisType }
        }
        delete obj.createTime
        let url = exportTable1()
        let url2 = exportTable2()
        this.downFile('get', url, obj, '总活跃用户数统计')
        this.downFile('get', url2, obj, '总活跃用户数统计')
      })
    },
    /* 搜索 */
    toSearch() {
      /*根据时间，判断日月周*/
      /*console.log(this.formInline.startTime, this.formInline.endTime)*/
      let { startDate: startTime, endDate: endTime } = this.formInline
      let s = new Date(startTime).getTime()
      let e = new Date(endTime).getTime()
      let d = (e - s) / (24 * 60 * 60 * 1000)
      if (d < 31) {
        //统计时间31天内，默认【天】统计
        this.activityAnalysisType = this.activityAnalysisTypeList[0].dictValue
      } else {
        //大于等于31天
        let threeMonth = this.moment(e).subtract(3, 'months')
        let isLimitThree = this.moment(threeMonth).isBefore(startTime)
        //统计时间31天-3个月，默认【周】统计;统计时间超过3个月，默认【月】单位统计
        this.activityAnalysisType = isLimitThree
          ? this.activityAnalysisTypeList[1].dictValue
          : (this.activityAnalysisType = this.activityAnalysisTypeList[2].dictValue)
      }
      this.clickSearch = true
      this.searchList()
    }
  }
}
</script>

<style lang="less">
#echartsList {
  #activityEcharts {
    width: 100%;
    height: 715px;
  }
  .date-btn {
    position: relative;
    float: right;
    margin-right: 10px;
    z-index: 1;
  }
}
</style>
